package cn.e4j.core.shiro.service.impl;

import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.IDto;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.shiro.service.UserAuthService;
import cn.e4j.core.util.SpringContextHolder;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.mapper.SysOrgMapper;
import cn.e4j.modular.system.mapper.SysUserMapper;
import cn.e4j.modular.system.mapper.SystemMapper;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Resource
    private SystemMapper systemMapper;

    public static UserAuthService me() {
        return SpringContextHolder.getBean(UserAuthService.class);
    }

    @Override
    public SysUser sysUser(String account) {

        SysUser user = sysUserMapper.getByAccount(account);

        // 账号不存在
        if (null == user) {
            throw new CredentialsException();
        }
        // 账号被冻结
        if (user.getSTATUS() == null || user.getSTATUS().equals("0")) {
            throw new LockedAccountException();
        }
        return user;
    }

    @Override
    public ShiroUser shiroUser(SysUser user) {

        ShiroUser shiroUser = new ShiroUser();

        BeanUtils.copyProperties(user, shiroUser);

        //Integer[] roleArray = Convert.toIntArray(user.getRoleid());
        List<Integer> roleList = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();
        //for (int roleId : roleArray) {
        //    roleList.add(roleId);
        //    roleNameList.add(ConstantFactory.me().getSingleRoleName(roleId));
        //}
        //shiroUser.setRoleList(roleList);
        //shiroUser.setRoleNames(roleNameList);
        shiroUser.setSysOrgT(sysOrgMapper.getByID(shiroUser.getORG_ID()));
        if(shiroUser.getDEVICE_ID()==null){
            //根据登录的id获取对应的授权组别列表
            List<String> permissions = Lists.newArrayList();
            List<Dto> devices = sysOrgMapper.getDevicesByUser_id(shiroUser.getID());
            for (Dto device : devices) {
                permissions.add(device.getString("DEVICE_ID"));
            }
            shiroUser.setDEVICE_ID(permissions);
        }
        if(shiroUser.getROLE_TYPE()==null){
            //根据用户id_获取所属角色的类型
            List<Dto> roles=sysOrgMapper.getRole_typeByUser_id(shiroUser.getID());
            String type_="";
            for (Dto role : roles) {
                type_ = type_ + role.getString("TYPE") + " | ";
            }
            type_= StringUtils.substringBeforeLast(type_, "|");
            shiroUser.setROLE_TYPE(type_);
        }

        return shiroUser;
    }

    @Override
    public List<String> findPermissionsByRoleId(Integer roleId) {
        //return menuMapper.getResUrlsByRoleId(roleId);
        return null;
    }

    @Override
    public String findRoleNameByRoleId(Integer roleId) {
        //return ConstantFactory.me().getSingleRoleTip(roleId);
        return null;
    }

    @Override
    public SimpleAuthenticationInfo info(ShiroUser shiroUser, SysUser user, String realmName) {
        String credentials = user.getPASSWORD();

        // 密码加盐处理
        //String source = user.getSalt();
        String source = ShiroKit.SALT;

        ByteSource credentialsSalt = new Md5Hash(source);

        return new SimpleAuthenticationInfo(shiroUser, credentials, credentialsSalt, realmName);

//        return new SimpleAuthenticationInfo(shiroUser, credentials, realmName);
    }

    @Override
    public List<String> getPermissionsByAccount(String account) {
        List<String> permissions = Lists.newArrayList();
        IDto inDto = Dtos.newDto("account", account);
        List<Dto> menus = systemMapper.getMenuPermissionsByAccount(inDto);
        for (Dto menu : menus) {
            permissions.add(menu.getString("PERMISSION"));
        }
        List<Dto> uis = systemMapper.getUIPermissionsByAccount(inDto);
        for (Dto ui : uis) {
            permissions.add(ui.getString("DOM_PERSSION"));
        }
        return permissions;
    }

}
